<?php
namespace Wechat\Controller;

use Wechat\Controller\AppController;
use Cake\Event\Event;
use Psr\Log\LogLevel;
use Cake\Network\Exception\NotFoundException;
use Cake\Routing\Router;

/**
 * 微信登录认证,新版微信登录规则：如果之前没有绑定，则自动注册一个账号，并绑定
 *
 * @property \Wechat\Controller\Component\WechatComponent $Wechat
 */
class LoginController extends AppController
{

    var $allowedActions = [
        'index',
        'callback'
    ];

    var $wxLoginActions = [];

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
    }

    /**
     * 登录默认跳转页面
     *
     * @link http://icoin.cjblog.org/wechat/login.html?redirect=/wechat/login/testresult.html
     * @link http://icoin.cjblog.org/wechat/login/testresult.html
     */
    public function index()
    {
        $wxcookieMember = $this->Cookie->read($this->wxloginCookiesKey);
        if (empty($wxcookieMember)) {
            $this->loadComponent('Wechat.Wechat', [
                'id' => $this->aId
            ]);
            // 跳转到登录界面,并保存返回地址
            $backurl = $this->request->getQuery("redirect", "/");
            $this->Cookie->configKey($this->return_url, 'expires', '+30 minutes');
            $this->Cookie->write($this->return_url, $backurl);
            $url = Router::url([
                'action' => 'callback',
                "_ext" => "html",
                "scope" => $this->request->getQuery("scope"),
                "app" => $this->aId
            ], true);
            $this->redirect($this->Wechat->getWxOauth(1, $url));
            return;
        }
        $this->redirect($this->Auth->redirectUrl());
    }

    /**
     * 登录回调
     *
     * @link http://icoin.cjblog.org/wechat/login/callback.html
     */
    public function callback()
    {
        $code = $this->request->getQuery("code", "");
        $scope = $this->request->getQuery("scope", ""); // scope=base 仅仅获取openid
        if (! empty($code)) {
            $this->loadComponent('Wechat.Wechat', [
                'id' => $this->aId
            ]);
            $result = $this->Wechat->getWxAccessToken($code);
            // $this->log($result, LogLevel::INFO);
            if (empty($result["openid"])) {
                throw new NotFoundException("请求不存在");
            }
            $islogin = $this->Wechat->findWxUserByOpenid($result["openid"]);
            if (empty($islogin->id) && strpos($result["scope"], "snsapi_userinfo") === false && $scope != "base") {
                // 从来没有授权获取用户信息,需要跳转
                $this->log("获取更高权限登录" . $result["openid"], LogLevel::INFO);
                $url = Router::url([
                    'action' => 'callback',
                    "_ext" => "html",
                    "app" => $this->aId
                ], true);
                $this->redirect($this->Wechat->getWxOauth(2, $url));
                return;
            }
            $this->log("正常登录之后保存信息" . $result["openid"], LogLevel::INFO);
            $cookie = [
                "id" => 0,
                "aid" => $this->aId,
                "openid" => $result["openid"]
            ];
            if ($scope != "base") {
                $this->log("更新用户信息", LogLevel::INFO);
                $uid = $this->Wechat->saveWeixinUser($result, $code);
                if (! empty($uid)) {
                    $cookie["id"] = $uid;
                }
            }
            $this->Cookie->write($this->wxloginCookiesKey, $cookie);
            $url = $this->Cookie->read($this->return_url);
            if (! empty($url)) {
                $this->Cookie->delete($this->return_url);
                $this->redirect($url);
                return;
            }
        }
    }
}
